import 'package:flutter/material.dart';
import 'package:flutter_app/View/MyLoader.dart';
import 'package:flutter_yfree/YFree.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

enum _MyRefresherLoadingState { Loading, Finish, Empty }

enum MyRefresherType { Up, Down, UpDown, None }

enum MyRefresherState { Up, Down }

class MyRefresherController {
  MyRefresherController({
    required this.state,
    required this.refreshController,
    required this.scrollController,
  });

  _MyRefresherState state;
  RefreshController refreshController;
  ScrollController scrollController;

  void reset() {
    refreshController.loadComplete();
    state.loadState = _MyRefresherLoadingState.Loading;
    try {
      state.setState(() {});
    } catch (e) {}
  }

  void loadFinish({bool showNoMoreData = false}) {
    state.loadState = _MyRefresherLoadingState.Finish;
    if (refreshController.isRefresh) {
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      if (showNoMoreData) {
        state.loadState = _MyRefresherLoadingState.Empty;
      }
    } else if (refreshController.isLoading) {
      refreshController.loadComplete();
      if (showNoMoreData) {
        refreshController.loadNoData();
      }
    } else {
      if (showNoMoreData) {
        state.loadState = _MyRefresherLoadingState.Empty;
      }
    }
    try {
      state.setState(() {});
    } catch (e) {}
  }

  void dispose() {}
}

class MyRefresher extends StatefulWidget {
  MyRefresher({
    required this.child,
    this.type = MyRefresherType.UpDown,
    this.onCreated,
    this.onPull,
    this.emptyImage,
    this.emptyTitle,
    this.emptyWidgetPaddingTop,
  });

  Widget child;
  MyRefresherType type;
  Function(MyRefresherController controller)? onCreated;
  Function(MyRefresherController controller, MyRefresherState state)? onPull;
  String? emptyImage;
  String? emptyTitle;
  double? emptyWidgetPaddingTop;

  @override
  State<MyRefresher> createState() => _MyRefresherState();
}

class _MyRefresherState extends State<MyRefresher> {
  late RefreshController refreshController;
  final scrollController = ScrollController();
  late MyRefresherController controller;

  _MyRefresherLoadingState loadState = _MyRefresherLoadingState.Loading;

  @override
  void initState() {
    super.initState();
    refreshController = RefreshController(initialRefresh: false);
    controller = MyRefresherController(
      state: this,
      refreshController: refreshController,
      scrollController: scrollController,
    );
    Future.delayed(Duration.zero, () => widget.onCreated?.call(controller));
  }

  @override
  void dispose() {
    refreshController.dispose();
    scrollController.dispose();
    super.dispose();
  }

  Widget view_content() {
    switch (loadState) {
      case _MyRefresherLoadingState.Loading:
        return Center(child: MyLoader());
      case _MyRefresherLoadingState.Finish:
        return SmartRefresher(
          controller: refreshController,
          scrollController: scrollController,
          enablePullDown: [MyRefresherType.Down, MyRefresherType.UpDown].contains(widget.type),
          enablePullUp: [MyRefresherType.Up, MyRefresherType.UpDown].contains(widget.type),
          physics: BouncingScrollPhysics(),
          header: WaterDropHeader(
            complete: SizedBox(width: 0, height: 0),
            waterDropColor: YConfig.themeColor,
            refresh: YCircularProgress(size: 20, strokeWidth: 2),
          ),
          footer: CustomFooter(
            height: 100,
            builder: (BuildContext context, LoadStatus? mode) {
              Widget? body;
              switch (mode) {
                case LoadStatus.idle:
                  break;
                case LoadStatus.canLoading:
                  body = Text("松手,加载更多!");
                  break;
                case LoadStatus.loading:
                  body = Column(
                    children: [
                      SizedBox(height: 5),
                      Container(width: 20, height: 20, child: YCircularProgress(strokeWidth: 2)),
                      SizedBox(height: 5),
                      Text('努力加载中', style: TextStyle(fontSize: 14, color: Color.fromARGB(255, 102, 102, 102))),
                    ],
                  );
                  break;
                case LoadStatus.noMore:
                  body = Column(
                    children: [
                      SizedBox(height: 5),
                      Icon(Icons.warning_amber_rounded, size: 20, color: Colors.grey),
                      SizedBox(height: 5),
                      Text('已经到底了', style: TextStyle(fontSize: 14, color: Color.fromARGB(255, 102, 102, 102))),
                    ],
                  );
                  break;
                case LoadStatus.failed:
                  body = Text("加载失败！点击重试！");
                  break;
                default:
                  break;
              }
              return SizedBox(height: 50.0, child: Center(child: body));
            },
          ),
          onRefresh: () => widget.onPull?.call(controller, MyRefresherState.Down),
          onLoading: () => widget.onPull?.call(controller, MyRefresherState.Up),
          child: widget.child,
        );
      case _MyRefresherLoadingState.Empty:
        return Container(
          alignment: (widget.emptyWidgetPaddingTop ?? 0) == 0 ? Alignment.center : Alignment.topCenter,
          child: Padding(
            padding: EdgeInsets.only(top: widget.emptyWidgetPaddingTop ?? 0),
            child: BlankPageWidget(imageStr: widget.emptyImage, tipsStr: widget.emptyTitle),
          ),
        );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: Theme.of(context).copyWith(colorScheme: ColorScheme.light(primary: YConfig.themeColor, secondary: YConfig.themeColor)),
      child: view_content(),
    );
  }
}

class BlankPageWidget extends StatelessWidget {
  const BlankPageWidget({
    this.tipsStr,
    this.imageStr,
  });

  final String? tipsStr;
  final String? imageStr;

  Widget buildIcon() {
    return Image.asset(imageStr ?? "images/bg_empty.png", fit: BoxFit.fitWidth);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: MediaQuery.of(context).size.width / 2,
          child: buildIcon(),
        ),
        Container(
          margin: EdgeInsets.only(top: 50),
          child: Text(tipsStr ?? "当前无数据", style: TextStyle(fontSize: 16, color: Colors.grey, fontWeight: FontWeight.w500)),
        ),
      ],
    );
  }
}
